﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using AvalonDock;
using RiskMan.Config;
using RiskMan.DataClass.Models;
using System.Windows.Threading;
using RiskMan.DataClass.Models.Quik;
using RiskMan.DataClass.Models.RM;
using RiskMan.Views.Dialogs;
using System.Reflection;

namespace RiskMan.Views.Stop
{
    /// <summary>
    /// Логика взаимодействия для StopView.xaml
    /// </summary>
    public partial class StopView : DocumentContent
    {
        private MainWindow mainWindow;
        private DispatcherTimer _dsUpdate;
        private string _formate;
        VerificationLicense vers = new VerificationLicense();


        public StopView ( )
        {
            mainWindow = MainWindow.StaticRiskMan;
            InitializeComponent( );
            this.Title = cfg.MainfunctionStop;

            
        }

        private void UpdataLines ( object sender, EventArgs args )
        {
            if (mainWindow._dataProvider != null)
            for ( int i = 0; i < mainWindow._dataProvider.StopList.Count; i++ )
            {
                mainWindow._dataProvider.StopList [ i ].CurrentPos = mainWindow._dataProvider.GetCurPosition(
                    mainWindow._dataProvider.StopList [ i ].Seccode,
                    mainWindow._dataProvider.StopList [ i ].Account,
                    mainWindow._dataProvider.StopList [ i ].ClientCode );
            }
        }

        private List<string> GetSeccodeList(ObservableCollection<CurrentParamModel> list)
        {
            List<String> result = new List<string>() { cfg.Unknown };

            for (int i = 0; i < list.Count; i++)
                result.Add(list[i].Seccode);

            return result;
        }

        public List<String> SeccodeList = new List<String>();

        private void Button_AddRow_Click(object sender, RoutedEventArgs e)
        {
            newStItem sni = new newStItem(new StopListModel(), mainWindow._dataProvider, false);
            sni.ShowDialog();
            if (sni.stop.Account != null)
                mainWindow._dataProvider.StopList.Add(sni.stop);
            update();
            cfg.SetLog("Добавлена строка в таблице стопов", mainWindow.ListBox_Logs, GetType(), MethodBase.GetCurrentMethod());
        }


        private List<string> GetClientCodes()
        {
            List<Trade> trades = new List<Trade>();
            List<String> result = new List<string>();

            for (int i = 0; i < mainWindow._dataProvider.T2QItems.Count; i++)
                for (int j = 0; j < mainWindow._dataProvider.T2QItems[i].TradeList.Count; j++)
                    trades.Add(mainWindow._dataProvider.T2QItems[i].TradeList[j]);

            foreach (var tmp in trades)
            {
                bool tr = false;
                foreach (var tm in result)
                {
                    if (tmp.ClientCode == tm)
                        tr = true;
                }
                if (tr == false)
                    result.Add(tmp.ClientCode);
            }

            return result;
        }

        private List<string> GetClientCodesForFilter()
        {
            List<Trade> trades = new List<Trade>();
            List<String> result = new List<string>();

            for (int i = 0; i < mainWindow._dataProvider.T2QItems.Count; i++)
                for (int j = 0; j < mainWindow._dataProvider.T2QItems[i].TradeList.Count; j++)
                    trades.Add(mainWindow._dataProvider.T2QItems[i].TradeList[j]);

            result.Add("Фильтр не выбран");

            foreach (var tmp in trades)
            {
                bool tr = false;
                foreach (var tm in result)
                {
                    if (tmp.ClientCode == tm)
                        tr = true;
                }
                if (tr == false)
                    result.Add(tmp.ClientCode);
            }

            result.Sort();
            return result;
        }
        private List<string> GetAccounts()
        {
            List<Trade> trades = new List<Trade>();
            List<String> result = new List<string>();

            for (int i = 0; i < mainWindow._dataProvider.T2QItems.Count; i++)
                for (int j = 0; j < mainWindow._dataProvider.T2QItems[i].TradeList.Count; j++)
                    trades.Add(mainWindow._dataProvider.T2QItems[i].TradeList[j]);

            foreach (var tmp in trades)
            {
                bool tr = false;
                foreach (var tm in result)
                {
                    if (tmp.Account == tm)
                        tr = true;
                }
                if (tr == false)
                    result.Add(tmp.Account);
            }

            return result;
        }

        private void update()
        {
            DataGrid_SL.ItemsSource = mainWindow._dataProvider.StopList;
        }

        private void TadeAccount_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((ComboBox)sender).SelectedValue.ToString() != cfg.Unknown)
            {
                string selected = ((ComboBox)sender).SelectedValue.ToString();

                List<string> clientCode = new List<string>();
                for (int i = 0; i < mainWindow._dataProvider.T2QItems.Count; i++)
                {
                    for (int j = 0; j < mainWindow._dataProvider.T2QItems[i].TradeList.Count; j++)
                    {
                        if (mainWindow._dataProvider.T2QItems[i].TradeList[j].Account == selected)
                        {
                            clientCode.Add(mainWindow._dataProvider.T2QItems[i].TradeList[j].ClientCode);
                        }
                    }
                }

                mainWindow._dataProvider.StopList[DataGrid_SL.SelectedIndex].ClientCodeList = clientCode;
                mainWindow._dataProvider.StopList[DataGrid_SL.SelectedIndex].ClientCode = cfg.Unknown;
            }
        }

        private void DataGrid_StopList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if ((sender as DataGrid).SelectedItems.Count == 1)
            {
                //for (int i = 0; i < mainWindow._dataProvider.StopList.Count; i++)
                //    if (((DataGrid)sender).Columns[)
                        

                newStItem sni = new newStItem(((DataGrid)sender).SelectedItem as StopListModel, mainWindow._dataProvider, true);
                sni.ShowDialog();

                int index = ((DataGrid)sender).SelectedIndex;
                for (int i = 0; i < mainWindow._dataProvider.StopList.Count; i++)
                    if (index == i)
                        mainWindow._dataProvider.StopList[i] = sni.stop;

                update();
                cfg.SetLog("Отредактирована строка в таблице стопов", mainWindow.ListBox_Logs, GetType(), MethodBase.GetCurrentMethod());
            }
        }

        #region Копировать строку в конец

        private void DataGrid_SL_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            if ((sender as System.Windows.Controls.DataGrid).SelectedItems.Count == 1)
            {
                int index = (sender as System.Windows.Controls.DataGrid).SelectedIndex + 1;
                DataGrid_SL.UnselectAll();
                if ( new DialogYesNo( "Вы действительно хотите скопировать строку " + index + "?", "Внимаение").Result == MessageBoxResult.Yes )
                {
                    var tmp = (StopListModel)cfg.DeepClone(mainWindow._dataProvider.StopList[index - 1 < 0 ? 0 : index - 1]);
                    if (tmp.IsStart == false)
                        mainWindow._dataProvider.StopList.Add(tmp);
                    else
                        new DialogOkCancel( "Для продолжения копирования нужно остановить копируемю строку", "Ошибка" );
                }
            }
        }

        private void button1_Click_1(object sender, RoutedEventArgs e)
        {
            if (DataGrid_SL.SelectedItems.Count == 1)
            {
                int index = DataGrid_SL.SelectedIndex + 1;
                DataGrid_SL.UnselectAll();
                if ( new DialogYesNo( "Вы действительно хотите скопировать строку " + index + "?", "Внимаение" ).Result == MessageBoxResult.Yes )
                {
                    var tmp = (StopListModel)cfg.DeepClone(mainWindow._dataProvider.StopList[index - 1 < 0 ? 0 : index - 1]);
                    if (tmp.IsStart == false)
                        mainWindow._dataProvider.StopList.Add(tmp);
                    else
                        new DialogOkCancel("Для продолжения копирования нужно остановить копируемю строку", "Ошибка");
                }
            }
        }

        #endregion

        /// <summary>
        /// Удаление строк стопов
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            List<int> tmpListNumbersStopList = new List<int>();
            bool flag;
            try
            {
                for (int i = 0; i < mainWindow._dataProvider.StopList.Count; i++)
                {
                    if (mainWindow._dataProvider.StopList[i].Check == true)
                    {
                        mainWindow._dataProvider.StopList.RemoveAt(i);
                        i--;
                    }
                }

                //добавлено мной, для удаления прошлых стоп-заявок из листа стоп-заявок
                for (int i = 0; i < mainWindow._dataProvider.StopLossOrderList.Count; i++)
			    {
                    flag = false;
                    for (int j = 0; j < mainWindow._dataProvider.StopList.Count; j++)
                        if (mainWindow._dataProvider.StopLossOrderList[i].ClientCode == mainWindow._dataProvider.StopList[j].ClientCode &&
                            mainWindow._dataProvider.StopLossOrderList[i].Seccode == mainWindow._dataProvider.StopList[j].Seccode)
                        {
                            flag = true;
                        }
                    if (flag == false)
                        tmpListNumbersStopList.Add(i);
			    }

                for (int i = tmpListNumbersStopList.Count-1; i >= 0; i--)
                {
                    mainWindow._dataProvider.StopLossOrderList.RemoveAt(tmpListNumbersStopList[i]);
                }
            }
            catch (Exception ex)
            {

            }
            update();
        }

        /// <summary>
        /// Отмечаем строки
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < mainWindow._dataProvider.StopList.Count; i++)
            {
                mainWindow._dataProvider.StopList[i].Check = (sender as CheckBox).IsChecked.Value;
            } 
            
            update();
        }

        /// <summary>
        /// Остановка
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, RoutedEventArgs e)
        {
            vers.RemoveAccountLicense(mainWindow, "SL");

            try
            {
                for (int i = 0; i < mainWindow._dataProvider.StopList.Count; i++)
                {
                    if (mainWindow._dataProvider.StopList[i].Check == true)
                    {
                        mainWindow._dataProvider.StopList[i].IsStart = false;
                    }
                }
            }
            catch (Exception ex)
            {

            }
            update();
        }




        /// <summary>
        /// Запуск
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click ( object sender, RoutedEventArgs e )
        {
            try
            {
                if (vers.CountAccountLicense(mainWindow, "SL") == false)
                {
                    new DialogOkCancel("Количество запускаемых счетов больше, чем приобретено лицензий. Одна лицензия - один счет ММВБ и один счет ФОРТС", "Предупреждение");
                    return;
                }
            }
            catch
            { 
            
            }

            try
            {
                bool tr = false;
                var list = mainWindow._dataProvider.StopList.Where( a => a.Check == true ).ToList( );
                for ( int i = 0; i < list.Count; i++ )
                {
                    if ( list [ i ].IsStart == false )
                    {
                        var tmp = mainWindow._dataProvider.StopList.Where( a => a.Seccode == list [ i ].Seccode &&
                                                  a.TypeStop == list [ i ].TypeStop &&
                                                  a.Account == list [ i ].Account &&
                                                  a.ClientCode == list [ i ].ClientCode &&
                                                  a.IsStart == true ).ToList( );
                        if ( tmp.Count != 0 )
                            tr = true;
                        else list [ i ].IsStart = true;
                    }
                }

                if ( tr == true )
                    new DialogMessage( "Несколько однаковых по типу, счету и бумаге стопов не могут быть запущены обновременно ", "Внимание!" );
            }
            catch ( Exception ex )
            {

            }
           // DataGrid_SL.ItemsSource = mainWindow._dataProvider.StopList;
        }

        private void DataGrid_SL_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void DataGrid_SL_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if ((sender as DataGrid).SelectedItems.Count == 1)
            {
                bool tr = mainWindow._dataProvider.StopList[(sender as DataGrid).SelectedIndex].Check == true ? false : true;
                mainWindow._dataProvider.StopList[(sender as DataGrid).SelectedIndex].Check = tr;
                GetFilterClientCode();
            }
            //DataGrid_SL.ItemsSource = mainWindow._dataProvider.StopList;
        }

        private void DataGrid_SL_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {

        }

        private void StopViewLayout_Loaded ( object sender, RoutedEventArgs e )
        {
            _dsUpdate = new DispatcherTimer( );
            _dsUpdate.Interval = cfg.UpdateStoptableInterval;
            _dsUpdate.Start( );
            _dsUpdate.Tick += new EventHandler( LogicMethod );
            _dsUpdate.Tick += new EventHandler( UpdataLines );

            SeccodeList = GetSeccodeList( mainWindow._dataProvider.CurrentList );

            DataGrid_SL.ItemsSource = mainWindow._dataProvider.StopList;

            cmbxFiltrAccount.ItemsSource = GetClientCodesForFilter();
            cmbxFiltrAccount.SelectedIndex = GetClientCodesForFilter().Count-1;
        }

        private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            GetFilterClientCode();
        }

        private void GetFilterClientCode()
        {
            if (cmbxFiltrAccount.SelectedItem.ToString() != "Фильтр не выбран")
                DataGrid_SL.ItemsSource = mainWindow._dataProvider.StopList.Where(a => a.ClientCode == cmbxFiltrAccount.SelectedItem.ToString()).ToList();
            else
                DataGrid_SL.ItemsSource = mainWindow._dataProvider.StopList;        
        }
    }
}
